package com.zwcl.common.component.thread.handler;

import com.alibaba.fastjson.JSON;
import com.zwcl.common.core.utils.ObjectMapUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * 公共HTTP请求抽象类
 */
@Slf4j
public abstract class AbstractHandle<Param, Response> implements IHandle<Param, Response> {

    // 真实请求url
    public String requestUrl;
    // 请求对象
    public Param param;
    // 响应对象
    public Response response;



    // 获取方法描述信息
    public abstract String getHandleDesc();
    // 获取url
    public abstract String getUrl();
    // 获取方法
    public abstract String getMethod();
    // 获取Response的class
    public abstract Class<Response> getResponseClass();
    // 校验参数 并且 返回
    public abstract Response checkAndReturn();
    // 构建请求头
    public abstract Map<String, String> buildHeader(Param param);
    // 构建请求体(map)
    public Map<String, Object> buildMapBody(Param param){
        Assert.notNull(param, "构建参数不能为空");
        return ObjectMapUtil.objectMap(param);
    }
    // 构建请求体(json)
    public String buildJSONBody(Param param) {
        Assert.notNull(param, "构建参数不能为空");
        return JSON.toJSONString(param);
    }


    @Override
    public IHandle<Param, Response> init(String host, Param param) {
        Assert.isTrue(StringUtils.isNotEmpty(host), "主机名不能为空");
        this.requestUrl = String.format(this.getUrl(), host);
        this.param = param;
        return this;
    }

    @Override
    public abstract IHandle<Param, Response> request();

    @Override
    public Response response() {
        return this.checkAndReturn();
    }


}
